import { Injectable } from '@nestjs/common';
import { CreateConfigCalcDto } from './dto/create-config_calc.dto';
import { UpdateConfigCalcDto } from './dto/update-config_calc.dto';
import { UserEntity } from 'src/user/entities/user.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { ConfigCalcEntity } from './entities/config_calc.entity';
import { Repository } from 'typeorm';
import { BusinessException } from 'src/common/filter/business-exception/business.exception';

@Injectable()
export class ConfigCalcService {
  constructor(
    @InjectRepository(ConfigCalcEntity)
    private readonly configCalcRepository: Repository<ConfigCalcEntity>,
  ) {}
  async create(createConfigCalcDto: CreateConfigCalcDto, user: UserEntity) {
    const config = await this.configCalcRepository.findOne({
      where: { user_id: user.id },
    });
    if (config) {
      throw new BusinessException('已有配置，不允许新增');
    }
    return await this.configCalcRepository.save({
      ...createConfigCalcDto,
      user_id: user.id,
    });
  }

  findAll() {
    return `This action returns all configCalc`;
  }

  async findOne(user: UserEntity) {
    const config = await this.configCalcRepository.findOne({
      where: { user_id: user.id },
    });
    if (!config)
      return await this.configCalcRepository.save({
        user_id: user.id,
      });
    return config;
  }

  async update(updateConfigCalcDto: UpdateConfigCalcDto, user: UserEntity) {
    const config = await this.configCalcRepository.findOne({
      where: { user_id: user.id },
    });
    if (!config) {
      throw new BusinessException('未找到配置，请先新增');
    }
    console.log('updateConfigCalcDto', updateConfigCalcDto);

    return await this.configCalcRepository.save({
      ...config,
      ...updateConfigCalcDto,
    });
  }

  // remove(id: number) {
  //   return `This action removes a #${id} configCalc`;
  // }
}
